/*
 * Copyright 2011-2012 OpenAjax Alliance
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

Components.utils.import("resource://oaa-cache-inspector/cache-inspector-common.js");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");


/**
 * @file sidebar-element-result-summary.js
 *
 * @desc Supports the sidebar showing rule summary information for a list if cache items 
 */

/* ---------------------------------------------------------------- */
/*            OAA_CI and OAA_CI.ElementResultView Object             */ 
/* ---------------------------------------------------------------- */

if (typeof OAA_CI === "undefined") {
  var OAA_CI = {};
}

if (typeof OAA_CI.ElementResultView === "undefined") {
  OAA_CI.ElementResultView = {};
}


/* ---------------------------------------------------------------- */
/*       Rule Category Cache Item Views and View Controllers        */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_CI.ElementResultView.init
 *
 * @desc Initializes the view
 */
 
OAA_CI.ElementResultView.init = function () {

  var doc = window.document;
  
  this.nls_strings               = doc.getElementById('ID_STRINGBUNDLE_LIST');
  
  this.vbox_element_result        = doc.getElementById('ID_VBOX_ELEMENT_RESULT_VIEW');
  
  this.label_node_result_selected = doc.getElementById('ID_LABEL_ELEMENT_RESULT_VIEW_SELECTED');
  this.label_node_result_element  = doc.getElementById('ID_LABEL_ELEMENT_RESULT_VIEW_ELEMENT');

  this.tree_node_result_details          = doc.getElementById('ID_TREE_ELEMENT_RESULT_VIEW');
  this.treechildren_node_result_details  = doc.getElementById('ID_TREECHILDREN_ELEMENT_RESULT_VIEW');
  
  this.button_rule_info          = doc.getElementById('ID_BUTTON_ELEMENT_RESULT_VIEW_SHOW_RULE');  
    
  this.node_results = [];
  this.node_result  = null;
  
  
  
};

/**
 * @function OAA_CI.ElementResultView.hide
 *
 * @desc Hides the element view controls
 */
 
OAA_CI.ElementResultView.hide = function () {

  this.vbox_element_result.hidden = true;
  
};


/**
 * @function OAA_CI.ElementResultView.show
 *
 * @desc Shows the element view controls
 */
 
OAA_CI.ElementResultView.show = function () {

  this.vbox_element_result.hidden = false;
  
};


/* ---------------------------------------------------------------- */
/*               Element Result View Functions                      */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_CI.ElementResultView.clear
 *
 * @desc Clears the node results from the tree
 */
 
OAA_CI.ElementResultView.clear = function () {

  this.node_results = [];
  this.node_result  = null;
  
  
  var nls_strings   = this.nls_strings;
  var treechildren  = this.treechildren_node_result_details;
  var label         = this.label_node_result_selected;
  var label_element = this.label_node_result_element;
  
  if (nls_strings && treechildren && label) {

//    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Clear 1: " + this.nls_strings.getString('noElementSelected'));
//    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Clear 2: " + this.nls_strings.getString('selectElement'));

    OAA_CI.removeChildNodes(treechildren);

    label.setAttribute('value', nls_strings.getString('ruleResultsElement'));
    if (label_element) label_element.setAttribute('value', "");
    
    var treeitem = document.createElement('treeitem');
    var treerow  = document.createElement('treerow');
          
    var treecell = document.createElement('treecell');
    treecell.setAttribute("label", nls_strings.getString('selectElement'));

    treerow.appendChild(treecell);      
    treeitem.appendChild(treerow);
    treechildren.appendChild(treeitem);

    OAA_CI.ElementResultView.ruleButtonClear();  
  } 
};

/**
 * @function OAA_CI.ElementResultView.update
 *
 * @desc Shows the node results of a cache item
 *
 * @param {CacheItemResult}  cache_item_result  - filtered cache item result object
 */
 
OAA_CI.ElementResultView.update = function (cache_item_result) {

  function addFilteredElementCount(count) {
    var str;
    
    if (count === 0) return;
    
    if (count === 1) str = count + " " + nls_strings.getString('filteredItem');
    else str = count + " "  + nls_strings.getString('filteredItems');
      
    OAA_CI.addTreeItemMessage(treechildren, str, 'filtered');

  }

  var SEVERITY = OpenAjax.a11y.SEVERITY;

  var nls_strings  = this.nls_strings;
  var tree         = this.tree_node_result_details;
  var treechildren  = this.treechildren_node_result_details;
  var label         = this.label_node_result_selected;
  var label_element = this.label_node_result_element;

  if (!treechildren || !nls_strings) return;

  OAA_CI.removeChildNodes(treechildren);

  this.node_results = [];
  this.node_result = null;

  if (cache_item_result && cache_item_result.cache_item) {
  
//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("# of Node Results: " + cache_item_result.node_results.length);

    var cache_item = cache_item_result.cache_item;
    
    var str = nls_strings.getString('ruleResultsElement') + " " + cache_item.position + " ";
    if (label) label.setAttribute('value', str);
    
    var MAX_LENGTH = 32;

    str = cache_item_result.cache_item.toString();    
    if (str.length > MAX_LENGTH) str = str.substring(0, (MAX_LENGTH/2)) + " ... " + str.substring(str.length-(MAX_LENGTH/2), str.length); 
    if (label_element) label_element.setAttribute('value', str);

    var n_results     = cache_item_result.node_results;
    var n_results_len = n_results.length;
        
    var n_result;
    var sev;
    var desc;

    var sub_treeitem;
    var sub_treerow;

    var sub_treecell;

    if (n_results_len) {
    
      for (var i = 0; i < n_results_len; i++) {
 
        n_result = n_results[i];

        n_result.position = (i + 1);
        this.node_results.push(n_result);

        var treeitem = document.createElement('treeitem');
        
        var open_flag = true;
        
        if (n_result.node_result_value == SEVERITY.PASS ||
            n_result.node_result_value == SEVERITY.HIDDEN) open_flag = false;
        
        if (n_result.cache_item.is_page_element) {
          treeitem.setAttribute('container', 'false');        
        }
        else {
          treeitem.setAttribute('container', 'true');
          if (open_flag) treeitem.setAttribute('open', 'true');
          else treeitem.setAttribute('open', 'false');
        }  
        
        var treerow  = document.createElement('treerow');

        var treecell = document.createElement('treecell');
        treecell.setAttribute('label',      n_result.getNLSSeverityLabel());
        treecell.setAttribute('properties', n_result.getSeverityStyle());
        treecell.setAttribute('value',      n_result.getRule().rule_id);
        treerow.appendChild(treecell);

        treecell = document.createElement('treecell');
        treecell.setAttribute('label', n_result.getMessage());
        treecell.setAttribute('properties', "message");
        treerow.appendChild(treecell);

        treeitem.appendChild(treerow);

        var sub_treechildren = document.createElement('treechildren');

        var properties = n_result.getRuleProperties();
        
        if (!n_result.cache_item.is_page_element) {
        
          for (var j = 0; j < properties.length; j++) {
 
            sub_treeitem = document.createElement('treeitem');
            sub_treerow  = document.createElement('treerow');

            sub_treecell = document.createElement('treecell');
 
            sub_treecell.setAttribute('label', properties[j].label);
            sub_treecell.setAttribute('value', n_result.rule_result.rule.rule_id);
            sub_treerow.appendChild(sub_treecell);
 
            sub_treecell = document.createElement('treecell');
        
            var label_text = properties[j].label;
            var value_text = properties[j].value;

//            OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("  j: " + j + " label: " + label_text + " value: " + value_text + " typeof Value: " + (typeof value_text) );
        
            if (value_text !== null) {
              // if value is a string test to see if it is empty
              if (typeof value_text == "string") {
                if (value_text.length) {
                  sub_treecell.setAttribute('label', value_text);
                } 
                else {
                  sub_treecell.setAttribute('label', nls_strings.getString('empty'));
                  sub_treecell.setAttribute('properties', 'empty');
                }
              }
              else {
                sub_treecell.setAttribute('label', value_text);
              }  
            }  
            else {
              sub_treecell.setAttribute('label', nls_strings.getString('undefined'));
              sub_treecell.setAttribute('properties', 'empty');
            }
        
            sub_treerow.appendChild(sub_treecell);
            sub_treeitem.appendChild(sub_treerow);    
            sub_treechildren.appendChild(sub_treeitem);
          } // end for  
        } 
          
        treeitem.appendChild(sub_treechildren);
        treechildren.appendChild(treeitem);
      }  
      
      addFilteredElementCount(cache_item_result.number_of_node_results_filtered);
      
    } 
    else {    
      if (cache_item_result.number_of_node_results_filtered) {
        addFilteredElementCount(cache_item_result.number_of_node_results_filtered);    
      }
      else {
        OAA_CI.addTreeItemMessage(treechildren, nls_strings.getString('noRuleResults'), '');
      }  
    
    }  
  }
  
  OAA_CI.ElementResultView.ruleButtonClear();
};


/**
 * @function OAA_CI.ElementResultView.nodeResultListOnSelect
 *
 * @desc Updates cache item information button when a cache item is selected
 */
 
OAA_CI.ElementResultView.onSelect = function () {

  var nls_strings  = OAA_CI.ElementResultView.nls_string;
  var tree         = OAA_CI.ElementResultView.tree_node_result_details;

  if (tree) {
  
    var index = tree.currentIndex;
 
    var cache_id = OAA_CI.getCacheIdFromTree(tree, index);
    
    if (!cache_id) return;
  
//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Index: " + index + " CACHE ID: " + cache_id);  


    if (cache_id === 'filtered') {
      OAA_CI.ElementResultView.elementButtonClear(); 
    }
    else {

      var node_results = OAA_CI.ElementResultView.node_results;
      var node_result  = null;

      for (var i = 0; i < node_results.length; i++ ) {
        if (cache_id == node_results[i].cache_id) {
          node_result = node_results[i];
          break;    
        }    
      } // end loop
      
      OAA_CI.ElementResultView.ruleButtonUpdate(node_result);  
    }  

//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug(" Node Result: " + node_result);  

    
  }
};

/**
 * @function OAA_CI.ElementResultView.showNodeResultInformation
 *
 * @desc Show information about the currently selected element 
 */
 
OAA_CI.ElementResultView.showNodeResultInformation = function () {

  var node_result = OAA_CI.ElementResultView.node_result;

  if (node_result) {
    OAA_CI.showRulePropertiesDialog(node_result);
  }
  else {
    OAA_CI_UTILS.preferencesDialog();
  }  

};

/* ---------------------------------------------------------------- */
/*                       Rule Information Button                    */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_CI.ElementResultView.ruleButtonClear
 *
 * @desc Clears the rules in the rules tabs
 */
 
OAA_CI.ElementResultView.ruleButtonClear = function () {

  if (this.nls_strings && this.button_rule_info) {
    this.button_rule_info.setAttribute("label", this.nls_strings.getString('rule') + ' ' + this.nls_strings.getString('information'));
    this.button_rule_info.setAttribute('tooltiptext', this.nls_strings.getString('noRuleSelected'));
    this.button_rule_info.setAttribute("disabled",    "true");
  }
  
  if (OAA_CI.rule_properties_dialog && 
      OAA_CI.rule_properties_dialog.rule_properties) {
    OAA_CI.rule_properties_dialog.rule_properties.clear();
  }

  this.node_result = null;

};

/**
 * @function OAA_CI.ElementResultView.ruleButtonUpdate
 *
 * @desc Updates the label of the show rule information button
 *
 * @param {NodeResult}  node_result  - Node result object    
 */
 
OAA_CI.ElementResultView.ruleButtonUpdate = function (node_result) {

  var label;

  if (this.nls_strings && this.button_rule_info) {
  
    this.node_result = node_result;
    
    if (node_result.getRuleSummary) {
    
      label = this.nls_strings.getString('moreInformationRule') + ": " + node_result.getRuleSummary();

      this.button_rule_info.setAttribute("label", this.nls_strings.getString('rule') + ' ' + node_result.position + ' ' + this.nls_strings.getString('information'));
      this.button_rule_info.setAttribute("tooltiptext",  label);
      this.button_rule_info.setAttribute("disabled", "false");

      if (OAA_CI.rule_properties_dialog && 
          OAA_CI.rule_properties_dialog.rule_properties) {
        OAA_CI.rule_properties_dialog.rule_properties.update(node_result);
      }

    }
    else {

      label = this.nls_strings.getString('noRuleSelected');

      this.button_rule_info.setAttribute("label", this.nls_strings.getString('rule') + ' ' + this.nls_strings.getString('information'));
      this.button_rule_info.setAttribute("tooltiptext",  label);
      this.button_rule_info.setAttribute("disabled", "true");
      
      if (OAA_CI.rule_properties_dialog && 
          OAA_CI.rule_properties_dialog.rule_properties) {
        OAA_CI.rule_properties_dialog.rule_properties.clear();
      }

    }
  
  }  
};

